
const olyModel = require('../model/olyModel.js');
const winningModel = require('../model/winningModel.js');
const shoppingModel = require('../model/shoppingModel.js');
const dateFormat = require('dateformat');

/**
 * 入会链接
 * @param {url: string} 回调链接
 */
exports.getMemberUrl = async (url, cloud) => {

    try {
        const result = await cloud.topApi.invoke({
            api: 'taobao.crm.member.joinurl.get',
            autoSession: true,
            data: {
                'callback_url': url,
                'extra_info': '{\"source\":\"isvapp\",\"activityId\":\"12345677\",\"entrance\":\"hudong\"}',
            }
        });
        return { isOk: 1, msg: '入会链接请求成功', data: result };
    } catch (err) {
        return { isOk: 0, msg: err };
    }
};

exports.addUser = async (param, cloud) => {
    let result = {
        isOk: 1,
        msg: '',
        data: param,
        date: new Date() > new Date("2020-11-04 00:00:00")
    };
    try {
        console.log("param===", param);
        // 获取用户头像
        let userCount = await olyModel.findCountByMixnick(param.mixNick, cloud)
        if (userCount == 0) {
            let user = await olyModel.createOne(param, cloud);
            if (user.insertId) {
                result.msg = '新增成功';
            } else {
                result.msg = '新增失败:' + user;
                result.isOk = 0;
            }
        } else {
            result.msg = '用户已存在'
        }
        return result
    } catch (err) {
        return { isOk: 0, msg: '铺捉到错误' + err };
    }
}


/**
   * 查看用户是否中奖
   */
exports.findUserWinning = async (param, cloud) => {
    let result = {
        code: '',
        msg: '',
        isOk: 1,
        data: {}
    };
    try {
        let winningObj = await winningModel.findUserWinning(param.mixNick, cloud);
        console.log("==winningObj===", winningObj);
        if (winningObj != null) {
            if (winningObj.name != null) {
                result.code = "10002";
                result.msg = "已中奖，并填写完信息";
                result.data = winningObj
            } else {
                result.code = "10003";
                result.msg = "已中奖，未填写信息";
            }
        } else {
            result.code = "10001";
            result.msg = "没有中奖";
        }

    } catch (err) {
        result.isOk = 0
        result.msg = err;
    }
    return result
}


/**
* 填写用户中奖信息
*/
exports.updateUserWinning = async (param, cloud) => {
    let result = {
        code: '',
        msg: '',
        isOk: 0
    };
    try {
        console.log("===========param===============", param)
        let updateObj = await winningModel.updateUserWinning(param, cloud);
        console.log("===========updateObj===============", updateObj)
        if (updateObj.affectedRows == 1) {
            result.code = "10000"
            result.msg = "填写成功";
        } else {
            result.code = "10002"
            result.msg = "没有中奖信息";
        }

    } catch (e) {
        result.isOk = 0
        result.msg = err;
    }
    return result
}


/**
   * 查看中奖信息
   */
exports.findWinning = async (cloud) => {
    let result = {
        msg: '',
        isOk: 0,
        data: []
    };
    try {
        let winningObj = await winningModel.findWinning(cloud);
        result.msg = "查询成功";
        result.isOk = 1;
        result.data = winningObj

    } catch (err) {
        result.msg = err;
    }
    return result
}



/**
   * 查看购物车
   */
exports.findCart = async (mixNick, cloud) => {
    let result = {
        msg: '',
        isOk: 0,
        data: null
    };
    try {

        let winningObj = await shoppingModel.findLastAddCartId(mixNick, cloud);
        console.log("============winningObj=========", winningObj)
        result.msg = "查询成功";
        result.isOk = 1;
        result.data = winningObj
        console.log()
    } catch (err) {
        result.msg = err;
    }
    return result
}


/**
   * 加购
   */
exports.addCart = async (params, cloud) => {
    try {
        let vip = await getMember(params.mixNick, cloud);
        console.log("-----------vipvipvipvip-------------", vip)
        // if (!vip) {
        //     return { isOk: 1, vip: false, msg: "不是会员" };
        // }
        console.log("------------", params)
        let itemIdArrayCopy = JSON.parse(params.itemId);
        // if (itemIdArrayCopy.length != itemIdArray.length) {
        //     return { isOk: 0, vip: true, msg: "有重复数据" };
        // }
        console.log("===========itemIdArrayCopy=============", itemIdArrayCopy)
        const cartId = ["563233800548", "569393324376", "583865198133", "563367801510", "623218137783", "624563864086", "563402710408", "579027757892"];


        for (let i = 0; i < itemIdArrayCopy.length; i++) {
            if (cartId.indexOf(itemIdArrayCopy[i]) == -1) {
                return { isOk: 0, vip: vip, msg: "无效数据" };
            }
        }
        let lastId = await shoppingModel.findLastAddCartId(params.mixNick, cloud);

        if (lastId) {
            return { isOk: 0, vip: vip, msg: "已经加购过" };
        }

        let userCount = await olyModel.findCountByMixnick(params.mixNick, cloud);
        console.log("----------------------", userCount)
        if (userCount) {
            let isFirst = 1;

            // console.log("=====lastId.length=======", lastId.length);
            // if (lastId.length > 0) {
            //     isFirst = lastId[0].isFirst + 1
            // }
            console.log("-------------params------", params)
            let addCartObj = {
                mixNick: params.mixNick,
                isFirst: isFirst,
                itemId: params.itemId,
                num: itemIdArrayCopy.length
            }
            let a = await shoppingModel.createOne(addCartObj, cloud);
            console.log('"=====================', a)
            return { isOk: 1, vip: vip, msg: "加购成功" };
        } else {
            return { isOk: 0, vip: vip, msg: "没有用户" };
        }
    } catch (err) {
        return { isOk: 0, msg: err };
    }
}



/**
   *
   * 抽奖
   *
   */
exports.winning = async (mixNick, cloud) => {
    const {
        ctx
    } = this;
    const result = {
        code: '',
        msg: ''
    };
    try {
        //查询符合抽奖资格的人群
   
        let shoppingFirstUserList = await shoppingModel.findWinning(cloud);
        for (let i = 0; i < shoppingFirstUserList.length; i++) {
            //生成中奖用户随机数
            let random = await randomNum(0, shoppingFirstUserList.length - 1)
             console.log("=============randomrandom===========", random);
            let winningUserInfo = shoppingFirstUserList[random];
            //是否是会员
            let vip = await getMember(winningUserInfo.mixNick, cloud);
            if (!vip) {
                continue;
            }
              console.log("=============vipvipvip===========", vip);
            let count = await winningModel.findCountByMixnick(winningUserInfo.mixNick, cloud);
             console.log("=============countcount===========", count);
            if (count == 0) {
                let tadnum = await winningModel.todayWinning(cloud)
                if (tadnum) {
                    return { code: '10002', msg: '当日已发奖' }
                }
                let resCount = await winningModel.createOne(winningUserInfo, cloud);
                console.log("=============resCount===========", resCount);
                if (resCount == null) {
                    continue;
                } else {
                    break;
                }
            }
        }
    } catch (e) {
        result.code = "10001"
        result.msg = e;
    }
    return result;
}


//埋点数据
exports.addUserStat = async (params, cloud) => {
    console.log("==============service==================")
    let reduceNum = await olyModel.addUserStat(params, dateFormat(new Date(), "yyyy-mm-dd hh:MM:ss"), cloud);
    if (reduceNum.affectedRows) {
        return { isOk: 1, msg: '添加成功' };
    }
};

//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
    console.log('----------------------------',arguments.length)
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        default:
            return 0;
    }
}







/**
 * 会员
 * @param {nickName: string} 明文nick
 * @param {session: string} 
 */
getMember = async (mix_nick, cloud) => {
    try {
        const result = await cloud.topApi.invoke({
            api: 'taobao.crm.member.identity.get',
            autoSession: true,
            data: {
                'mix_nick': mix_nick,
            }
        });
        console.log(mix_nick, "-----------resultresultresult-------------", result)
        return result.result.member_info ? true : false
    } catch (err) {
        return { isOk: 0, msg: err };
    }
};

